package com.example.ipservice;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
public class IPController {

    @GetMapping("/")
    public String getClientIP(HttpServletRequest request) {
        String clientIP = getClientIpFromXForwardedFor(request.getHeader("X-Forwarded-For"));
        return "客户端IP: " + clientIP + ", 服务器IP: " + getServerIP();
    }

    private String getClientIpFromXForwardedFor(String xffHeader) {
        if (xffHeader == null || xffHeader.isEmpty() || "unknown".equalsIgnoreCase(xffHeader)) {
            return "无法确定";
        }
        // 处理多级代理的情况，取第一个IP（客户端真实IP）
        String[] ips = xffHeader.split(",");
        for (String ip : ips) {
            if (!"unknown".equalsIgnoreCase(ip.trim())) {
                return ip.trim();
            }
        }
        return "无法确定";
    }

    private String getServerIP() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            return "无法获取服务器IP";
        }
    }

    @GetMapping("/ip/details")
    public Map<String, Object> getIpDetails(HttpServletRequest request) {
        Map<String, Object> details = new LinkedHashMap<>();
        details.put("ip", getClientIP(request));
        details.put("userAgent", request.getHeader("User-Agent"));
        details.put("serverTime", LocalDateTime.now());
        return details;
    }

    @GetMapping("/headers")
    public Map<String, String> showHeaders(HttpServletRequest request) {
        Map<String, String> headers = new LinkedHashMap<>();
        Collections.list(request.getHeaderNames())
            .forEach(header -> headers.put(header, request.getHeader(header)));
        return headers;
    }

    @GetMapping("/time")
    public String showServerTime() {
        return "当前服务器时间: " + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }
}